﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace itChatAdmin
{
    public partial class FromGroupAdmin : Form
    {
        public FromGroupAdmin()
        {
            InitializeComponent();
        }
        String UserType = "0";
        String UserID = "";
        String NickName ="";
        String UserName ="";

        private void Refresh_ChatRooms_List()
        {
            this.listView1.Items.Clear();

            String Filter = this.textBox1.Text.Trim();
            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", Form1.memSQLiteConnection);
            if (Filter == "")
            {
                mySQLiteCommand.CommandText = "SELECT ID,NickName,MemberCount,IsOwner,IsEnabled,IsGetStrangers FROM MelaGroups";
            }
            else
            {
                mySQLiteCommand.CommandText = "SELECT ID,NickName,MemberCount,IsOwner,IsEnabled,IsGetStrangers FROM MelaGroups WHERE NickName like '%" + Filter + "%'";

            }
            SQLiteDataReader mySQLiteDataReader = mySQLiteCommand.ExecuteReader();
            while (mySQLiteDataReader.Read())
            {
                String ID = mySQLiteDataReader["ID"].ToString().Trim();
                String NickName = mySQLiteDataReader["NickName"].ToString().Trim();
                String MemberCount = mySQLiteDataReader["MemberCount"].ToString().Trim();
                String IsOwner = mySQLiteDataReader["IsOwner"].ToString().Trim();
                Boolean IsEnabled = Boolean.Parse(mySQLiteDataReader["IsEnabled"].ToString().Trim());
                Boolean IsGetStrangers = Boolean.Parse(mySQLiteDataReader["IsGetStrangers"].ToString().Trim());

                if (IsOwner == "1")
                {
                    NickName += "(群主)";
                }

                int GroupsIndex = 0;

                if (IsEnabled == true)
                {
                    GroupsIndex = 0;
                }
                else
                {
                    GroupsIndex = 1;
                }
                ListViewItem item = new ListViewItem(new string[] { ID, NickName, MemberCount }, 0, this.listView1.Groups[GroupsIndex]);
                //if (IsGetStrangers == false)
                //{
                //    item.BackColor = Color.Silver;
                //}
                this.Invoke((EventHandler)delegate { listView1.Items.Add(item); });
            }
        }
       

        private void button16_Click(object sender, EventArgs e)
        {
            Form1.Refresh_Group();
            Refresh_ChatRooms_List();
        }

        private void button11_Click(object sender, EventArgs e)
        {
            Refresh_ChatRooms_List();
        }

        private void button14_Click(object sender, EventArgs e)
        {
            //发送一条测试信息

            String Msg = Form1.GetOneMelaMessages(this.textBox10.Text);
            if (Msg == "") return;

            //发送一条
            Object command = new
            {
                cmd = WX_COMMAND.send_msg.ToString(),
                data_0 = Msg,
                data_1 = UserName,
                data_2 = "",
                data_3 = ""

            };
            //向服务器发送数据
            String result = Form1.SendCommnadTo_itChat(command);
            //MessageBox.Show(result);

            Form1.InsetIntoLogs(UserType, NickName, Msg, result);
            Form1.Write_Log(result, WX_COMMAND.send_msg.ToString(), 4);
            RefreshGroupLogs();
        }

        private void button28_Click(object sender, EventArgs e)
        {
            //保存配置
            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", Form1.memSQLiteConnection);
            int IsEnabled = 0;
            int IsGetStrangers = 0;
            if (this.checkBox1.Checked)
            {
                IsEnabled = 1;
            }
            if (this.checkBox3.Checked)
            {
                IsGetStrangers = 1;
            }
            mySQLiteCommand.CommandText = "UPDATE MelaGroups SET IsEnabled='" + IsEnabled + "',IsGetStrangers='" + IsGetStrangers + "',MsgClass='" + this.textBox10.Text + "',SendTimes='" + this.textBox5.Text + "' WHERE ID='" + UserID + "'";
            mySQLiteCommand.ExecuteNonQuery();
            Form1.WriteToDBInDisk(mySQLiteCommand);

            //刷新
            Refresh_ChatRooms_List();
            MessageBox.Show("保存成功！");
        }

        private void 启用发送ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedIndices != null && listView1.SelectedIndices.Count > 0)
            {
                ListView.SelectedIndexCollection c = listView1.SelectedIndices;
                String ItemIndex = listView1.Items[c[0]].Text;
                Update_MelaGroups(ItemIndex, "IsEnabled");
                Refresh_ChatRooms_List();
                RefreshGroupLogs();
            }
        }

        private void RefreshGroupLogs()
        {
            //更新發送日誌
            this.Invoke((EventHandler)delegate
            {
                listView2.Items.Clear();
                this.textBox5.Text = "";
                this.textBox10.Text = "";
            });

            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", Form1.memSQLiteConnection);
            mySQLiteCommand.CommandText = "SELECT * FROM MelaSendMsgLog WHERE UserType=@UserType AND NickName=@NickName";
            mySQLiteCommand.Parameters.Add(new SQLiteParameter("@UserType"));
            mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));
            mySQLiteCommand.Parameters["@UserType"].Value = UserType;
            mySQLiteCommand.Parameters["@NickName"].Value = NickName;
            SQLiteDataReader mySQLiteDataReader3 = mySQLiteCommand.ExecuteReader();
            mySQLiteCommand.Parameters.Clear();

            while (mySQLiteDataReader3.Read())
            {
                String ID = mySQLiteDataReader3["ID"].ToString().Trim();
                String SendDateTime = mySQLiteDataReader3["UpdateDataTime"].ToString().Trim();
                String MsgID = mySQLiteDataReader3["SendMsg"].ToString().Trim();
                String SendResult = mySQLiteDataReader3["SendResult"].ToString().Trim();

                ListViewItem item = new ListViewItem(new string[] { ID, SendDateTime, MsgID, SendResult });

                this.Invoke((EventHandler)delegate
                {
                    listView2.Items.Add(item);
                });
            }
            mySQLiteDataReader3.Close();


            //更新右键选项
            mySQLiteCommand.CommandText = "SELECT * FROM MelaGroups WHERE NickName=@NickName";
            mySQLiteCommand.Parameters.Add(new SQLiteParameter("@NickName"));
            mySQLiteCommand.Parameters["@NickName"].Value = NickName;
            SQLiteDataReader mySQLiteDataReader1 = mySQLiteCommand.ExecuteReader();
            if (mySQLiteDataReader1.Read())
            {
                Boolean IsEnabled = Boolean.Parse(mySQLiteDataReader1["IsEnabled"].ToString().Trim());
                Boolean IsGetStrangers = Boolean.Parse(mySQLiteDataReader1["IsGetStrangers"].ToString().Trim());
                String NickName = mySQLiteDataReader1["NickName"].ToString().Trim();
                String MsgClass = mySQLiteDataReader1["MsgClass"].ToString().Trim();
                String SendTimes = mySQLiteDataReader1["SendTimes"].ToString().Trim();

                启用发送ToolStripMenuItem.Checked = IsEnabled;
                过滤陌生人ToolStripMenuItem.Checked = IsGetStrangers;

                this.Invoke((EventHandler)delegate
                {
                    this.checkBox1.Checked = IsEnabled;
                    this.checkBox3.Checked = IsGetStrangers;
                    this.label29.Text = NickName;
                    this.textBox10.Text = MsgClass;
                    this.textBox5.Text = SendTimes;
                });

                //更新选择框
                string[] msg = MsgClass.Split('|');

                for (int j = 0; j < this.checkedListBox1.Items.Count; j++)
                {
                    this.checkedListBox1.SetItemChecked(j, false);
                }

                foreach (String m in msg)
                {
                    if (m == "") continue;
                    for (int j = 0; j < checkedListBox1.Items.Count; j++)
                    {
                        if (checkedListBox1.Items[j].ToString() == m)
                        {
                            checkedListBox1.SetItemChecked(j, true);
                        }
                    }
                }
            }
            mySQLiteDataReader1.Close();

            //更新未来发送的计划
            this.listView3.Items.Clear();
            int i = 0;
            foreach (DataRow row in Form1.MsgSendTable.Select("", "SendTime asc"))
            {
                if (row["UserName"].ToString().Trim() != UserName)
                {
                    continue;
                }
                i++;
                ListViewItem item = new ListViewItem(new string[] {
                    i.ToString().Trim(),
                    row["SendTime"].ToString().Trim(),
                    row["MsgClass"].ToString().Trim(),
                    });

                if (Boolean.Parse(row["IsFinished"].ToString().Trim()) == true)
                {
                    item.BackColor = Color.LightGray;
                }

                this.Invoke((EventHandler)delegate
                {
                    listView3.Items.Add(item);
                });
            }

        }
        private void Update_MelaGroups(String ID, String Clo)
        {
            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", Form1.memSQLiteConnection);
            mySQLiteCommand.CommandText = "update MelaGroups set " + Clo + "=(not " + Clo + ") where id=" + ID;
            mySQLiteCommand.ExecuteNonQuery();
            Form1.WriteToDBInDisk(mySQLiteCommand);
        }

        private void 过滤陌生人ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedIndices != null && listView1.SelectedIndices.Count > 0)
            {
                ListView.SelectedIndexCollection c = listView1.SelectedIndices;
                String ItemIndex = listView1.Items[c[0]].SubItems[0].Text;
                Update_MelaGroups(ItemIndex, "IsGetStrangers");
                Refresh_ChatRooms_List();
                RefreshGroupLogs();
            }
        }

        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            foreach (ListViewItem lv in this.listView1.Items)
            {
                lv.BackColor = Color.White;
            }

            if (listView1.SelectedIndices != null && listView1.SelectedIndices.Count > 0)
            {
                ListView.SelectedIndexCollection c = listView1.SelectedIndices;
                listView1.Items[c[0]].BackColor = Color.Silver;
                UserID = listView1.Items[c[0]].SubItems[0].Text;
                NickName = listView1.Items[c[0]].SubItems[1].Text.Replace("(群主)", "");
                UserName = Form1.GetGroupUserNameWithID(UserID);
                RefreshGroupLogs();
            }
        }

        private void listView2_DoubleClick(object sender, EventArgs e)
        {
            if (listView2.SelectedIndices != null && listView2.SelectedIndices.Count > 0)
            {
                ListView.SelectedIndexCollection c = listView2.SelectedIndices;
                String ID = listView2.Items[c[0]].SubItems[0].Text;
                FormLogView fl = new FormLogView(ID);
                fl.ShowDialog();
            }
        }

        private void textBox10_Click(object sender, EventArgs e)
        {
            if (this.checkedListBox1.Visible)
            {
                //添加变量
                this.textBox10.Text = "";
                string MsgClassValue = "";
                foreach (var a in checkedListBox1.CheckedItems)
                {
                    MsgClassValue += a.ToString() + "|";
                }

                if (MsgClassValue != "")
                {
                    this.textBox10.Text = MsgClassValue.Substring(0, MsgClassValue.Length - 1);
                }
                this.checkedListBox1.Visible = false;
            }
            else
            {
                this.checkedListBox1.Visible = true;
            }
        }

        private void FromGroupAdmin_Load(object sender, EventArgs e)
        {
            Refresh_ChatRooms_List();
            RefreshGroupLogs();

            this.checkedListBox1.Items.Clear();
            SQLiteCommand mySQLiteCommand = new SQLiteCommand("", Form1.memSQLiteConnection);
            mySQLiteCommand.CommandText = "SELECT * FROM MelaMessagesClass ORDER BY ClassName";
            SQLiteDataReader mySQLiteDataReader1 = mySQLiteCommand.ExecuteReader();
            while (mySQLiteDataReader1.Read())
            {
                this.checkedListBox1.Items.Add(mySQLiteDataReader1["ClassName"].ToString().Trim());
            }
            mySQLiteCommand.Parameters.Clear();
            mySQLiteDataReader1.Close();
        }

        private void checkedListBox1_Click(object sender, EventArgs e)
        {
            string MsgClassValue = "";
            foreach (var a in checkedListBox1.CheckedItems)
            {
                MsgClassValue += a.ToString() + "|";
            }
            if (MsgClassValue != "")
            {
                this.textBox10.Text = MsgClassValue.Substring(0, MsgClassValue.Length - 1);
            }
            else
            {
                this.textBox10.Text = MsgClassValue;
            }
        }

    }
}
